const path = require('path');
const Koa = require('koa');
const fs = require('fs');
const static = require('koa-static');
// const views = require('koa-views');
const bodyParser = require('koa-bodyparser');
const logger = require('koa-logger');
const cors = require('@koa/cors');
const config = require('./config/config');
const router = require('./router');
const app = new Koa();
const Send = require('./middlewares/send');
require('./config/mongoose.js'); // 必须要在入口文件引，否则数据库连接不上


// 处理跨域，先行注释后期优化
// const ALLOWORIGIN = ['*']
// app.use(cors({
//   origin: ctx => {
//     if (ALLOWORIGIN.includes(ctx.header.origin)) return ctx.header.origin;
//   }
// }))

app.use(cors({origin: '*'}))
app.use(logger()); // 配置控制台日志中间件
app.use(Send())
app.use(bodyParser());

// 处理静态资源
app.use(static(__dirname + '/dist'));

// 处理模板引擎
// app.use(views(path.join(__dirname, './views'), {extension: 'html'}));



app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    console.log("统一错误捕获中间件捕获到的错误---------", err);
    ctx.response.status = 200;
    ctx.response.body = {
      message: err.message
    }
  }
})

app
  .use(router.routes())
  .use(router.allowedMethods());

// // 处理前端 react history 路由
app.use(async ctx => {
  ctx.type = 'html';
  ctx.body = fs.createReadStream(`./dist/index.html`);
})


app.listen(config.port);
console.log('the server is start at port %s', config.port);
